package com.hxc.shop.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Component
public class FileUtil {


    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    /**
     * @param ins 文件输入流
     * @param file 文件
     * @description 获取流文件
     * */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param filePath pdf路径
     * @param fileName 文件名
     * @description 根据路径和文件名导出文件
     * */
    public static void exportFile(String filePath, String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                //处理文件名中文乱码
                String realName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                String userAgent = request.getHeader("User-agent");
                //判断浏览器代理并分别设置响应给浏览器的编码格式
                String finalFileName;
                if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE浏览器
                    finalFileName = URLEncoder.encode(realName,"UTF8");
                }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
//                    finalFileName = new String(realName.getBytes(), "UTF8");
                    finalFileName = new String(realName.getBytes(), "ISO8859-1");
                }else{
                    finalFileName = URLEncoder.encode(realName,"UTF8");//其他浏览器
                }
                response.reset();
                response.addHeader("Content-Disposition", "attachment;filename=\"" +finalFileName+ "\"");
                response.setContentType("application/octet-stream");
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * @param filePath 文件路径
     * @param file 文件
     * @description 将文件保存到指定路径
     * */
    public static String saveFile(String filePath, MultipartFile file) throws IOException {
        String path = filePath + System.currentTimeMillis()/1000 + "/";
        File fileDirty = new File(path);
        if (!fileDirty.exists()) {
            fileDirty.mkdirs();
        }
        String FILEPATH = path + file.getOriginalFilename();
        File outFile = new File(FILEPATH);
        FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
        return FILEPATH;
    }

}
